package com.repro.lib_base.bases.activity

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * 基类Activity 默认支持viewBinding
 * VB不能为空
 */
abstract class BaseActivity<VB : ViewBinding> : BaseStateActivity() {

    open lateinit var binding: VB

    /**
     * 创建mContentView
     */
    override fun createContainerView(toolbarView: ToolBarView?) {

        binding = getViewBindingForActivity(layoutInflater)
        mContentView = binding.root
        setContentView(mContentView)

        val toolBar = toolbarView?.onCreateToolBar(layoutInflater, this)
        //界面添加toolbar
        toolBar?.let {
            rootView.addView(
                toolBar, ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    toolbarView.getToolbarHeightSpan()
                )
            )
            //是否偏移量
            mContentView.layoutParams = toolbarView.contentTopMarginLayoutParams(isEnableFitSystemWindows)
        }
    }

    /**
     * 通过viewBinding实现mContentView
     */
    @Suppress("UNCHECKED_CAST")
    private fun getViewBindingForActivity(layoutInflater: LayoutInflater): VB {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as VB
    }
}